package com.wyw.leetcode.learning.medium;

import java.util.HashSet;
import java.util.Set;

/**
 * leetcode topic 3
 * 无重复字符的最长子串
 *
 * @Author Mr Wu （yewen.wu.china@gmail.com）
 * @Date 2021/11/10 16:35
 */
public class Topic003 {
    public static void main(String[] args) {
        String s = "hello world";
        String s1 = "abcabcbb";
        String s2 = "bbbb";
        String s3 = "abcadefgh";
        System.out.println(lengthOfLongestSubstring(s));
        System.out.println(lengthOfLongestSubstring(s1));
        System.out.println(lengthOfLongestSubstring(s2));
        System.out.println(lengthOfLongestSubstring1(s));
        System.out.println(lengthOfLongestSubstring2(s3));
    }

    public static int lengthOfLongestSubstring(String s) {
        if(s == null || s == "") {
            return 0;
        }
        int start = 0;
        int result = 1;
        int length = s.length();
        while (start + result <= length) {
            String temp = s.substring(start, start+result);
            if(containRepeatChar(temp)) {
                start ++;
            } else {
                result ++;
            }
        }
        return --result;
    }

    public static int lengthOfLongestSubstring1(String s) {
        // 记录字符上一次出现的位置
        int[] last = new int[128];
        for(int i = 0; i < 128; i++) {
            last[i] = -1;
        }
        int n = s.length();

        int res = 0;
        int start = 0; // 窗口开始位置
        for(int i = 0; i < n; i++) {
            int index = s.charAt(i);
            start = Math.max(start, last[index] + 1);
            res   = Math.max(res, i - start + 1);
            last[index] = i;
        }

        return res;
    }
    public static int lengthOfLongestSubstring2(String s) {
        // 哈希集合，记录每个字符是否出现过
        Set<Character> occ = new HashSet<Character>();
        int n = s.length();
        // 右指针，初始值为 -1，相当于我们在字符串的左边界的左侧，还没有开始移动
        int rk = -1, ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i != 0) {
                // 左指针向右移动一格，移除一个字符
                occ.remove(s.charAt(i - 1));
            }
            while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                // 不断地移动右指针
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            // 第 i 到 rk 个字符是一个极长的无重复字符子串
            ans = Math.max(ans, rk - i + 1);
        }
        return ans;
    }

    //判断是否有重复字符
    public static boolean containRepeatChar(String str){
        if(str==null||str.isEmpty()){
            return false;
        }
        char[] elements=str.toCharArray();
        for(char e:elements){
            if(str.indexOf(e)!=str.lastIndexOf(e)){
                return true;
            }
        }
        return false;
    }
}
